<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleTabClick">
      <el-tab-pane label="供应商来料批合格率目标" name="1"></el-tab-pane>
      <el-tab-pane label="首件检验批合格率目标" name="2"></el-tab-pane>
      <el-tab-pane label="OQC批合格率目标" name="4"></el-tab-pane>
      <el-tab-pane label="FQC批合格率目标" name="5"></el-tab-pane>
      <el-tab-pane label="制程检验批合格率" name="3"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :search.sync="query"
      :page.sync="page"
      ref="crud"
      @selection-change="selectionChange"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @cell-click="cellClick"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDel">删除</el-button>
      </template>
    </avue-crud>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.url"
      :params="importConfig.params"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey" />
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import importDialogComp from '@/components/dialog/import/index.vue';
import userConfig from '@/mixins/userConfig';
import { CancelToken } from 'axios';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { addOrUpdate, getList, remove } from '@/api/report/qualityQualificationManage';
const QUERY_TYPE_MAP = {
  1: 'IQC',
  2: 'FAI',
  3: 'IPQC',
  4: 'CQC',
  5: 'FQC'
};
export default {
  name: 'qualityQualificationManage', // 会渲染成传入的componentName
  components: {
    CommonModalTemplate,
    userTableConfig,
    importDialogComp
  },

  mixins: [userConfig()],
  data() {
    return {
      form: {},
      modalName: '', //打开公用模态框名称
      tableOption: {},
      type: '',
      visibile: false,
      currentIndex: -1,
      timer: new Date().getTime(),
      importConfig: {
        show: false,
        title: '供应商来料批合格率目标导入',
        exportName: '供应商来料批合格率目标模板.xlsx',
        url: '',
        params: {}
      },
      cancel: null,
      activeName: '1',
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      selectionList: [],
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 540px)',
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        selection: true,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: true,
        addRowBtn: true,
        cellBtn: true,
        delBtn: true,
        addBtn: false,
        indexLabel: '序号',
        searchLabelWidth: 120,
        columnBtn: false,
        column: [
          {
            label: '供应商编码',
            prop: 'objectCode',
            search: true,
            searchSpan: 6,
            searchOrder: 3,
            cell: true,
            disabled: true,
            type: 'search',
            searchType: 'input',
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openVendorCommonModal();
            }
          },
          {
            label: '供应商名称',
            prop: 'objectName',
            cell: true,
            searchSpan: 6,
            search: true,
            disabled: true,
            searchOrder: 2,
            width: 230
          },
          {
            label: '供应商类型',
            prop: 'objectType',
            cell: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=partner_type',
            search: true,
            disabled: true,
            searchSpan: 6,
            searchOrder: 1,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '批合格率目标值',
            prop: 'passRateTargetValue',
            type: 'number',
            cell: true,
            rules: [
              {
                required: true,
                message: '批合格率目标值不能为空',
                trigger: 'blur'
              }
            ],
            formatter: (val) => {
              return val.passRateTargetValue + '%';
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      return this.selectionList.map((ele) => ele.id);
    }
  },
  methods: {
    async rowSave(row, done, loading) {
      const data = {
        ...row,
        targetType: QUERY_TYPE_MAP[this.activeName]
      };
      try {
        const res = await addOrUpdate(data);
        this.$message.success('保存成功');
        done();
        this.onLoad(this.page);
      } catch (e) {
        console.warn(e);
        loading();
      }
    },
    async rowUpdate(row, index, done, loading) {
      const data = {
        ...row,
        targetType: QUERY_TYPE_MAP[this.activeName]
      };
      try {
        const res = await addOrUpdate(data);
        this.$message.success('保存成功');
        done();
        this.onLoad(this.page);
      } catch (e) {
        console.warn(e);
        loading();
      }
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    cellClick(row, column, cell, event) {
      this.currentIndex = row.$index;
    },
    handleTabClick() {
      this.data = [];
      const supplyColumn = [
        {
          label: '供应商编码',
          prop: 'objectCode',
          search: true,
          searchSpan: 6,
          searchOrder: 3,
          cell: true,
          disabled: true,
          type: 'search',
          searchType: 'input',
          rules: [
            {
              required: true,
              message: '请输入编码',
              trigger: 'blur'
            }
          ],
          appendClick: () => {
            this.openVendorCommonModal();
          }
        },
        {
          label: '供应商名称',
          prop: 'objectName',
          cell: true,
          searchSpan: 6,
          search: true,
          disabled: true,
          searchOrder: 2,
          width: 230
        },
        {
          label: '供应商类型',
          prop: 'objectType',
          cell: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=partner_type',
          search: true,
          disabled: true,
          searchSpan: 6,
          searchOrder: 1,
          props: {
            label: 'dictValue',
            value: 'dictKey'
          }
        },
        {
          label: '批合格率目标值',
          prop: 'passRateTargetValue',
          type: 'number',
          cell: true,
          rules: [
            {
              required: true,
              message: '批合格率目标值不能为空',
              trigger: 'blur'
            }
          ],
          formatter: (val) => {
            return val.passRateTargetValue + '%';
          }
        }
      ];
      const firstColumn = [
        {
          label: '产线名称',
          prop: 'objectName',
          search: true,
          searchSpan: 6,
          searchOrder: 3,
          searchType: 'input',
          disabled: true,
          type: 'search',
          cell: true,
          appendClick: () => {
            this.openLineCommonModal();
          }
        },
        {
          label: '批合格率目标值',
          prop: 'passRateTargetValue',
          cell: true,
          type: 'number',
          rules: [
            {
              required: true,
              message: '批合格率目标值不能为空',
              trigger: 'blur'
            }
          ],
          formatter: (val) => {
            return val.passRateTargetValue + '%';
          }
        }
      ];
      const shipmentColumn = [
        {
          label: '产线名称',
          prop: 'objectName',
          appendClick: () => {
            this.openLineCommonModal();
          },
          search: true,
          searchSpan: 6,
          searchOrder: 3,
          searchType: 'input',
          type: 'search',
          cell: true,
          disabled: true,
          rules: [
            {
              required: true,
              message: '请输入编码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '批合格率目标值',
          prop: 'passRateTargetValue',
          cell: true,
          type: 'number',
          rules: [
            {
              required: true,
              message: '批合格率目标值不能为空',
              trigger: 'blur'
            }
          ],
          formatter: (val) => {
            return val.passRateTargetValue + '%';
          }
        }
      ];
      const colMap = {
        1: supplyColumn,
        2: firstColumn,
        3: shipmentColumn,
        4: shipmentColumn,
        5: shipmentColumn
      };
      this.query = {};
      this.$set(this.option, 'column', colMap[this.activeName]);
      this.$set(this.query, 'objectName', '');
      this.handleCancelRequest();
      this.$refs.crud.refreshTable();
      this.onLoad(this.page);
    },
    handleCancelRequest() {
      this.cancel('取消请求');
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        params.targetType = QUERY_TYPE_MAP[this.activeName];
        const res = await getList({ cancelToken: new CancelToken((c) => (this.cancel = c)) }, page.currentPage, page.pageSize, Object.assign(params, this.query));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    handleGotoInspect(row) {
      this.$router.push({
        path: '/quality/overTimeWaitInspect',
        query: {
          partNo: encodeURIComponent(row.partNo)
        }
      });
    },
    rowView(row) {
      this.detailQuery = row;
      this.showDetailDialog = true;
    },
    codeClose(value) {
      if (value) {
        this.onLoad(this.page);
      }
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleImport() {
      this.importConfig.show = true;
      const map = {
        1: '供应商来料批合格率目标',
        2: '首件检验批合格率目标',
        3: '制程检验批合格率目标',
        4: 'OQC批合格率目标',
        5: 'FQC批合格率目标'
      };
      this.importConfig = {
        show: true,
        title: `${map[this.activeName]}导入`,
        exportName: `${map[this.activeName]}模板.xlsx`,
        url: `/api/mes-product/qms/quality/target/management/excel/import`,
        params: { targetType: QUERY_TYPE_MAP[this.activeName] }
      };
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/partner/page?multiPartnerType=SUPPLIER,MANUFACTURER,OUTSOURCING',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '类型',
            prop: 'partnerType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=partner_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    openLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      let url = '';
      url = '/api/mes-product/productionline/page';
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      if (this.modalName === 'vendorModal') {
        if (this.data[this.currentIndex].id) {
          const oldData = this.data[this.currentIndex];
          const newData = Object.assign(oldData, { objectCode: rowData.partnerNo, objectType: rowData.partnerType, objectName: rowData.name, objectId: rowData.id });
          this.data.splice(this.currentIndex, 1, newData);
        } else {
          this.$refs.crud.rowCellAdd({
            objectCode: rowData.partnerNo,
            objectType: rowData.partnerType,
            objectName: rowData.name,
            objectId: rowData.id,
            $cellEdit: true
          });
          this.data.splice(this.currentIndex, 1);
        }
      } else {
        if (this.data[this.currentIndex].id) {
          const oldData = this.data[this.currentIndex];
          const newData = Object.assign(oldData, { objectName: rowData.name, objectCode: rowData.code, objectId: rowData.id });
          this.data.splice(this.currentIndex, 1, newData);
        } else {
          this.$refs.crud.rowCellAdd({
            objectName: rowData.name,
            objectCode: rowData.code,
            objectId: rowData.id,
            $cellEdit: true
          });
          this.data.splice(this.currentIndex, 1);
        }
      }
    },
    handleDel() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    }
  }
};
</script>
<style lang="scss" scoped></style>
